﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Data.SqlClient;
using Microsoft.SharePoint.Utilities;
using System.IO;
using System.Xml.Serialization;
using VPLink2013.Framework;
using VPLink2013.Framework.Constants;
using VPLink2013.Framework.Extensions;
using Microsoft.Office.Server.SocialData;

namespace VPLink2013.Webpart
{
    public class NewsVP : WebpartVPLink
    {
        StringBuilder sbLogins = new StringBuilder();
        private int LengthTitreCourt = 58;
        private bool NewsOnly2LevelActive = false;
        private bool ShowCountComments = false;
        private bool NewsAll = false;
        private SocialCommentManager commentsManager = new SocialCommentManager();

        bool GroupeALaUne = false;
        bool GroupeN2 = false;
        bool GroupeN3 = false;
        bool GroupeN4 = false;
        int CompteurDerniersArticles = 5;
        int CompteurGroupe2 = 0;

        #region get HTML
        /// <summary>
        /// Returns the HTML code rendered by this web part
        /// </summary>
        /// <returns>HTL code as string</returns>
        protected override string GetHtml()
        {
            string strHtml = string.Empty;
            ContextTrace.PrefixFileName = "webpart NewsVP";

            string strHtmlFileCache = string.Empty;
            string login = VPLink2013XsltTransformHelper.StringAfter(this.Context.User.Identity.Name);
            try
            {
                global = new GlobalVPLink2013();
                global.ListeAnnonces = new List<Annonce>();

                string strUrl = ParamSharepointSite;
                ContextTrace.AddTrace("strUrl : " + strUrl);
                
                string strXslFileName = "NewsVP.xsl";
                
                bool FileCacheFound = false;

                strFileCacheUtilisateur = pathCache + @"\MenuGeneralUtilisateur\MenuGeneral_"
                    + login + ".xml";
                FileSerialization.CheckFileCacheExists(strFileCacheUtilisateur, 60 * 12);

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    if (UtilisateurCrt == null)
                    {
                        UtilisateurCrt = new Utilisateur();
                        UtilisateurCrt.Login = this.Context.User.Identity.Name;
                    }
                    SetUtilisateurCrt();
                });

                using (SPSite site = new SPSite(strUrl))
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        string strPage = this.Context.Request.Url.AbsolutePath.ToLower();

                        SPList lstConfig = web.Lists.TryGetList(ListTitles.ConfigurationVPTitle);

                        bool isFrenchVersion = true;
                        SPSecurity.RunWithElevatedPrivileges(delegate(){
                            ProcessConfigurationVP(lstConfig);
                        });

                        if (SPContext.Current.ContextPageInfo.IsWebWelcomePage)
                        {
                            SPSecurity.RunWithElevatedPrivileges
                            (delegate()
                            {
                                isFrenchVersion = UtilisateurCrt.Pays.Equals("France", StringComparison.CurrentCultureIgnoreCase);
                                strHtmlFileCache = pathCache + @"\NewsVP\NewsVP_Interne" + UtilisateurCrt.IsInterne + ".htm";
                                FileSerialization.CheckFileCacheExists(strHtmlFileCache, 1);
                            });

                            if (System.IO.File.Exists(strHtmlFileCache) && false) // ça passe pas !
                            {
                                strHtml = System.IO.File.ReadAllText(strHtmlFileCache);
                                //ContextTrace.AddTrace("File cache found !");
                                FileCacheFound = true;
                            }
                            else
                            {
                                strFileCacheUtilisateur = pathCache + @"\MenuGeneralUtilisateur\MenuGeneral_"
                                   + login + ".xml";
                                FileSerialization.CheckFileCacheExists(strFileCacheUtilisateur, 60 * 12);
                                isFrenchVersion = UtilisateurCrt.Pays.Equals("France", StringComparison.CurrentCultureIgnoreCase);


                                SPList lst = web.Lists.TryGetList(ListTitles.NewsVPTitle);
                                if (lst != null)
                                {
                                    ProcessNewsVP(lst, isFrenchVersion);
                                }
                                strXslFileName = "NewsVP.xsl";
                            }
                        }
                        else
                        {
                            ContextTrace.PrefixFileName = "webpart NewsVP(List)";
                            SPList lst = web.Lists.TryGetList(ListTitles.NewsVPTitle);
                            ProcessNewsVPList(lst, isFrenchVersion);
                            strXslFileName = "NewsVPList.xsl";
                        }

                        SPSecurity.RunWithElevatedPrivileges
                        (delegate()
                        {
                            ProcessLike(lstConfig);
                        });
                    }

                    if (!FileCacheFound)
                    {
                        string strXml = FileSerialization.CreateXmlStringFromObj(global);

                        string strXslPath = pathVP + @"\XSL\NewsVP\" + strXslFileName;
                        //ContextTrace.AddTrace("GetHtml.strXslPath = " + strXslPath);
                        strHtml = VPLink2013XsltTransformHelper.GetTransform(strXml, strXslPath, StringAfter(UtilisateurCrt.Login), pathTemp);
                        if (strHtmlFileCache != "")
                        {
                            SPSecurity.RunWithElevatedPrivileges
                            (delegate()
                            {
                                TraceFile(strHtmlFileCache, strHtml);
                            });
                        }
                    }
                }
            }
            catch (System.Exception exc)
            {
                ContextTrace.AddTrace("Erreur GetHtml : " + exc.Message + "/" + exc.StackTrace);
            }
            ContextTrace.PrefixFileName = "webpart NewsVP";
            return strHtml;
        }
        #endregion get HTML

        private void ProcessLike(SPList lstConfig)
        {
            string ConfigLike = GetValueConfigurationVP(lstConfig, "Like");
            // Inactif : do not display like component 
            // Article seul : can be clicked on only details page
            // Partout : can be clicked on in home page
            if (ConfigLike == "Inactif")
            {
                ContextTrace.AddTrace("ProcessLike.RETURN : ConfigLike != Actif : " + ConfigLike);
                return;
            }

            global.ConfigurationVP = new ConfigurationVP();
            global.ConfigurationVP.Like = ConfigLike;

            StringBuilder sbIdAnnonces = new StringBuilder();
            foreach (Annonce ann in global.ListeAnnonces)
            {
                if (sbIdAnnonces.Length > 0)
                {
                    sbIdAnnonces.Append(", ");
                }
                sbIdAnnonces.Append(ann.ID);
            }

            string strIdAnnonces = sbIdAnnonces.ToString();
            if (string.IsNullOrEmpty(strIdAnnonces))
            {
                ContextTrace.AddTrace("ProcessLike.RETURN : string.IsNullOrEmpty(strIdAnnonces)");
                return;
            }
            string strSql = "SELECT IdArticle, NbLike, UsersLike, DateLike FROM LikeArticle WHERE UrlSite like '" + ParamSharepointSite + "' and IdArticle IN (" + strIdAnnonces + ")";
            SqlConnection conn = VPLink2013SqlHelper.GetConnection(connectionString);
            SqlCommand command = VPLink2013SqlHelper.GetCommand(conn, strSql);
            SqlDataReader Reader = command.ExecuteReader();
            string strUserCrtLogin = FormatLogin(this.Context.User.Identity.Name);

            // Loop through annonce already liked
            while (Reader.Read())
            {
                int idArticle = VPLink2013SqlHelper.GetValueReaderInt(Reader, 0);
                int nbLike = VPLink2013SqlHelper.GetValueReaderInt(Reader, 1);
                string UsersLike = VPLink2013SqlHelper.GetValueReader(Reader, 2);
                string DateLike = VPLink2013SqlHelper.GetValueReader(Reader, 3);

                //ContextTrace.AddTrace("strUserCrtLogin : " + strUserCrtLogin);

                string strIdArticle = idArticle.ToString();
                Annonce ann = (from u in global.ListeAnnonces where u.ID == strIdArticle select u).FirstOrDefault();
                if (ann != null)
                {
                    // Nb Like
                    ann.NbLike = nbLike.ToString();
                    ContextTrace.AddTrace("ann.ID : " + ann.ID + " => ann.NbLike : " + ann.NbLike);

                    // Current user has already liked annonce
                    string UsersLikeFormat = "," + UsersLike + ",";
                    string UserLoginFormat = "," + strUserCrtLogin + ",";

                    if (UsersLikeFormat.Contains(UserLoginFormat))
                    {
                        ann.LikeUserCrt = "OK";
                    }
                }
            }
            VPLink2013SqlHelper.CloseReader(conn, Reader);
            try
            {
                processLikeAction(strUserCrtLogin);
            }
            catch (Exception ex)
            {
            }
        }

        public string FormatLogin(string login)
        {
            string strLogin = login;
            int iPos = strLogin.IndexOf(@"\");
            if (iPos > 0)
            {
                strLogin = strLogin.Substring(iPos + 1);
            }
            return strLogin;
        }

        private void processLikeAction(string strUserCrtLogin)
        {
            string strAction = ParamFrm("MyAction");
            string likedAnnonce = ParamFrm("likedAnnonceID");
            string UsersLike = string.Empty;
            string DateLike = string.Empty;

            if (strAction == "jaime" && !string.IsNullOrEmpty(likedAnnonce))
            {
                Annonce ann = (from u in global.ListeAnnonces
                               where u.ID == likedAnnonce
                               select u).FirstOrDefault();

                // get annonce from sql
                string strSql = "SELECT IdArticle, NbLike, UsersLike, DateLike FROM LikeArticle WHERE UrlSite like '" + ParamSharepointSite + "' and IdArticle = " + ann.ID;
                SqlConnection conn = VPLink2013SqlHelper.GetConnection(connectionString);
                SqlCommand command = VPLink2013SqlHelper.GetCommand(conn, strSql);
                SqlDataReader Reader = command.ExecuteReader();

                ContextTrace.AddTrace("Action jaime à traiter");
                if (!Reader.HasRows)
                {
                    // first like => insert new line
                    UsersLike = strUserCrtLogin;
                    DateLike = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
                    ann.NbLike = "1";
                    strSql = "INSERT INTO LikeArticle (UrlSite, NomListe, IdArticle, TitreArticle, NbLike, UsersLike, DateLike) "
                        + " VALUES ('" + ParamSharepointSite + "', 'NewsVP', " + ann.ID + ", '" + ann.Titre.Replace("'", "''") + "', 1, '" + UsersLike + "', '" + DateLike + "')";
                }
                else
                {
                    strSql = string.Empty;
                    while (Reader.Read())
                    {
                        UsersLike = VPLink2013SqlHelper.GetValueReader(Reader, 2);
                        DateLike = VPLink2013SqlHelper.GetValueReader(Reader, 3);
                        ann.NbLike = VPLink2013SqlHelper.GetValueReaderInt(Reader, 1).ToString();
                    }
                    // not first like => update line
                    string UsersLikeFormat = "," + UsersLike + ",";
                    string UserLoginFormat = "," + strUserCrtLogin + ",";
                    if (!UsersLikeFormat.Contains(UserLoginFormat))
                    {
                        ann.NbLike = (Int32.Parse(ann.NbLike) + 1).ToString();
                        UsersLike += "," + strUserCrtLogin;
                        DateLike += "," + DateTime.Now.ToString("dd/MM/yyyy HH:mm");
                        strSql = "UPDATE LikeArticle SET NbLike = " + ann.NbLike
                            + ", UsersLike = '" + UsersLike + "'"
                            + ", DateLike = '" + DateLike + "'"
                            + " WHERE UrlSite like '" + ParamSharepointSite + "' and IdArticle = " + ann.ID;
                    }
                }
                VPLink2013SqlHelper.CloseReader(conn, Reader);
                if (!string.IsNullOrEmpty(strSql))
                {
                    SqlConnection connUpdate = VPLink2013SqlHelper.GetConnection(connectionString);
                    SqlCommand commandUpdate = VPLink2013SqlHelper.GetCommand(connUpdate, strSql);
                    commandUpdate.ExecuteNonQuery();
                    connUpdate.Close();
                    ann.LikeProcessed = "OK";
                }
                ann.LikeUserCrt = "OK";
            }
        }

        private void ProcessConfigurationVP(SPList lst)
        {
            Dictionary<string, string> likeConfigurationDictionnary = new Dictionary<string, string>()
            {

            };
            string configComment = GetValueConfigurationVP(lst, Fields.ConfigCommentsKeyName);
            try
            {
                ShowCountComments = bool.Parse(configComment);
            }
            catch(Exception ex)
            {
                ContextTrace.AddTrace("Erreur.ProcessConfigurationVP Compteur Commentaires: " + ex.Message);
            }
            string strValeur = GetValueConfigurationVP(lst, "NombreDerniersArticles");
            //string strValeur = GetValueConfigurationVP(lst, "Like"); //Actif, Inactif
            ContextTrace.AddTrace("ProcessConfigurationVP.strValeur : " + strValeur);
            try
            {
                CompteurDerniersArticles = int.Parse(strValeur);
            }
            catch (System.Exception exc)
            {
                ContextTrace.AddTrace("Erreur.ProcessConfigurationVP CompteurDerniersArticles: " + exc.Message);
            }

            strValeur = GetValueConfigurationVP(lst, "NewsOnly2Level");
            ContextTrace.AddTrace("ProcessConfigurationVP.strValeur : " + strValeur);
            try
            {
                NewsOnly2LevelActive = bool.Parse(strValeur);
            }
            catch (System.Exception exc)
            {
                ContextTrace.AddTrace("Erreur.ProcessConfigurationVP NewsOnly2LevelActive: " + exc.Message);
            }
            try
            {
                strValeur = GetValueConfigurationVP(lst, "NewsAll");
                NewsAll = bool.Parse(strValeur);
            }
            catch (System.Exception exc)
            {
                ContextTrace.AddTrace("Erreur.ProcessConfigurationVP NewsAll: " + exc.Message);
            }

        }

        private string GetFilAriane(string strCategorie)
        {
            string strLinkAccueil = ParamSharepointSite + "/pages/default.aspx";

            StringBuilder sbFilAriane = new StringBuilder();
            sbFilAriane.AppendLine("<div class=\"breadcrumbs\">");
            sbFilAriane.AppendLine("<span><a href=\"" + strLinkAccueil + "\">Accueil</a></span>");
            sbFilAriane.AppendLine("&nbsp;>&nbsp");
            sbFilAriane.AppendLine("<span>News</span>");
            if (strCategorie != "")
            {
                sbFilAriane.AppendLine("&nbsp;>&nbsp");
                sbFilAriane.AppendLine("<span>" + strCategorie + "</span>");
            }
            sbFilAriane.AppendLine("</div>");
            return sbFilAriane.ToString();
        }

        private void ProcessNewsVPList(SPList lst, bool isFrenchVersion)
        {
            string strListe = lst.Title;
            SPQuery spQuery = new SPQuery();
            StringBuilder sb = new StringBuilder();

            MenuInterneAnnonce mei = new MenuInterneAnnonce();
            mei.ParamSharepointSite = ParamSharepointSite;
            //mei.PathCache = PathCache;
            //mei.PathVP = PathVP;
            //mei.PathTemp = PathTemp;
            //mei.ContextTrace = ContextTrace;

            global.Filtre = new Filtre();
            global.Filtre.Titre = ParamFrm("FiltreNewsTitre");
            if (global.Filtre.Titre == "Rechercher une news")
            {
                global.Filtre.Titre = string.Empty;
            }

            global.Filtre.MenuInterne = mei.GetHtmlMenuAnnonces();

            string strCategorieCrt = ParamFrm("Categorie");
            string strMoisCrt = ParamFrm("MoisCrt");

            global.Filtre.FilAriane = GetFilAriane(strCategorieCrt);
            global.Filtre.Categorie = GetControlHidden("Categorie", strCategorieCrt);
            global.Filtre.MoisCrt = GetControlHidden("MoisCrt", strMoisCrt);

            string strDateCrt = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now);
            sb.Append("<Where>");
            if (global.Filtre.Titre != "")
            {
                sb.AppendLine("<And>");
                sb.AppendLine("<Or>");
                sb.AppendLine("     <Contains><FieldRef Name='Title'/><Value Type='Text'>" + global.Filtre.Titre + "</Value></Contains>");
                sb.AppendLine("     <Or>");
                sb.AppendLine("         <Contains><FieldRef Name='Chapeau'/><Value Type='Text'>" + global.Filtre.Titre + "</Value></Contains>");
                sb.AppendLine("         <Or>");
                sb.AppendLine("             <Contains><FieldRef Name='Categorie'/><Value Type='Text'>" + global.Filtre.Titre + "</Value></Contains>");
                sb.AppendLine("             <Or>");
                sb.AppendLine("                 <Contains><FieldRef Name='Theme'/><Value Type='Text'>" + global.Filtre.Titre + "</Value></Contains>");
                sb.AppendLine("                 <Or>");
                sb.AppendLine("                     <Contains><FieldRef Name='Surtitre'/><Value Type='Text'>" + global.Filtre.Titre + "</Value></Contains>");
                sb.AppendLine("                     <Contains><FieldRef Name='Body'/><Value Type='Text'>" + global.Filtre.Titre + "</Value></Contains>");
                sb.AppendLine("                 </Or>");
                sb.AppendLine("             </Or>");
                sb.AppendLine("         </Or>");
                sb.AppendLine("     </Or>");
                sb.AppendLine("</Or>");
            }
            if (strCategorieCrt != "")
            {
                sb.AppendLine("<And>");
                sb.AppendLine("<Eq><FieldRef Name='Categorie'/><Value Type='Text'>" + strCategorieCrt + "</Value></Eq>");
            }
            if (strMoisCrt != "")
            {
                DateTime dtDateDebutMoisCrt = DateTime.Parse(strMoisCrt);
                DateTime dtDateFinMoisCrt = dtDateDebutMoisCrt.AddMonths(1).AddHours(-5);

                string strDateDebutMoisCrt = SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtDateDebutMoisCrt);
                string strDateFinMoisCrt = SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtDateFinMoisCrt);

                sb.AppendLine("<And>");
                sb.AppendLine("     <And>");
                sb.AppendLine("         <Geq><FieldRef Name='Date_x0020_publication'/><Value Type='DateTime' IncludeTimeValue='True'>" + strDateDebutMoisCrt + "</Value></Geq>");
                sb.AppendLine("         <Leq><FieldRef Name='Date_x0020_publication'/><Value Type='DateTime' IncludeTimeValue='True'>" + strDateFinMoisCrt + "</Value></Leq>");
                sb.AppendLine("     </And>");
            }
            sb.AppendLine("<And>");
            sb.AppendLine("     <Eq><FieldRef Name='En_x0020_ligne'/><Value Type='Text'>Oui</Value></Eq>");
            sb.AppendLine("     <Or>");
            sb.AppendLine("         <Leq><FieldRef Name='Date_x0020_publication'/><Value Type='DateTime' IncludeTimeValue='True'>" + strDateCrt + "</Value></Leq>");
            sb.AppendLine("         <IsNull><FieldRef Name='Date_x0020_publication'/></IsNull>");
            sb.AppendLine("     </Or>");
            sb.AppendLine("</And>");
            if (strMoisCrt != "")
            {
                sb.AppendLine("</And>");
            }
            if (!string.IsNullOrEmpty(strCategorieCrt))
            {
                sb.AppendLine("</And>");
            }
            if (!string.IsNullOrEmpty(global.Filtre.Titre))
            {
                sb.AppendLine("</And>");
            }
            sb.AppendLine("</Where>");
            sb.AppendLine("<OrderBy><FieldRef Name='Date_x0020_publication' Ascending='FALSE'/><FieldRef Name='ID' Ascending='FALSE'/></OrderBy>");

            if (global.Filtre.Titre == "")
            {
                global.Filtre.Titre = "Rechercher une news";
            }

            string Query = sb.ToString();
            spQuery.Query = Query;
            ContextTrace.AddTrace("spQuery.Query : " + spQuery.Query);

            SPListItemCollection items = lst.GetItems(spQuery);
            ContextTrace.AddTrace("items.Count : " + items.Count.ToString());

            if (items.Count == 0 && strMoisCrt != "")
            {
                if (global.Context == null)
                {
                    global.Context = new Context();
                }
                global.Context.Message = "Aucune archive pour le mois selectionné";
            }

            string strPageCrt = ParamFrm("PageCrt");

            int iPageCrt = 1;
            if (strPageCrt != "")
            {
                iPageCrt = int.Parse(strPageCrt);
            }
            global.Filtre.PageCrt = GetControlHidden("PageCrt", iPageCrt.ToString());

            int iPagePrec = 0;
            int iPageSuiv = 0;

            int iNbPerPage = 5;

            int iCrt = 1;
            int iStart = (iPageCrt - 1) * iNbPerPage + 1;
            int iEnd = iPageCrt * iNbPerPage;

            ContextTrace.AddTrace("iStart : " + iStart.ToString());
            ContextTrace.AddTrace("iEnd : " + iEnd.ToString());

            foreach (SPListItem item in items)
            {
                ContextTrace.AddTrace("iCrt : " + iCrt.ToString());
                if (iCrt < iStart)
                {
                    iPagePrec = iPageCrt - 1;
                    ContextTrace.AddTrace("iPagePrec : " + iPagePrec.ToString());
                }
                if (iCrt > iEnd)
                {
                    iPageSuiv = iPageCrt + 1;
                    ContextTrace.AddTrace("iPageSuiv : " + iPageSuiv.ToString());
                }
                if (iCrt >= iStart && iCrt <= iEnd)
                {
                    Annonce ann = GetAnnonceFromNewsItem(item, isFrenchVersion);

                    global.ListeAnnonces.Add(ann);
                }
                iCrt += 1;
            }

            #region Paging
            if (iPagePrec > 0 || iPageSuiv > 0)
            {
                StringBuilder sbNavigationPages = new StringBuilder();
                sbNavigationPages.AppendLine("<div class=\"pages_news\">");

                if (iPagePrec > 0)
                {
                    sbNavigationPages.AppendLine("<a href=\"javascript:GoToPage(" + iPagePrec.ToString() + ");\">");
                    sbNavigationPages.AppendLine("<img src=\"/_layouts/15/VPLink2013/Images/pages_news_left.jpg\" width=\"6\" height=\"11\">");
                    sbNavigationPages.AppendLine("   Page précédente");
                    sbNavigationPages.AppendLine("</a>");
                }
                if (iPagePrec > 0 && iPageSuiv > 0)
                {
                    sbNavigationPages.AppendLine("<span>|</span>");
                }
                if (iPageSuiv > 0)
                {
                    sbNavigationPages.AppendLine("<a href=\"javascript:GoToPage(" + iPageSuiv.ToString() + ");\">");
                    sbNavigationPages.AppendLine("Page suivante   ");
                    sbNavigationPages.AppendLine("<img src=\"/_layouts/15/VPLink2013/Images/pages_news_right.jpg\" width=\"6\" height=\"11\">");
                    sbNavigationPages.AppendLine("</a>");
                }
                sbNavigationPages.AppendLine("</div>");

                global.Filtre.NavigationPages = sbNavigationPages.ToString();
                global.Filtre.NavigationPagesBottom = sbNavigationPages.ToString().Replace("\"pages_news\"", "\"pages_news pages-bottom\"");
            }
            #endregion
        }

        private Annonce GetAnnonceFromNewsItem(SPListItem item, bool isFrenchVersion)
        {
            Annonce ann = new Annonce();
            ann.ID = item.ID.ToString();
            Uri uriSite = new Uri(ParamSharepointSite);
            Uri annonceUri = new Uri(uriSite, "/Pages/AnnonceDetail2013.aspx?ItemID=" + ann.ID);
            ann.LinkDetail = annonceUri.ToString();
            if (commentsManager != null && ShowCountComments)
            {
                ann.CountComments = commentsManager.GetCount(annonceUri).ToString();
            }
            ann.Surtitre = item.GetItemListFieldValueAsText(Fields.SurtitreNewsField);
            if (isFrenchVersion)
            {
                ann.Titre = item.GetItemListFieldValueAsText(Fields.TitleField);
                ann.Chapeau = item.GetItemListFieldValueAsHtml(Fields.ChapeauNewsField);
                if (string.IsNullOrEmpty(ann.Titre) || string.IsNullOrEmpty(ann.Chapeau))
                {
                    ann.Titre = item.GetItemListFieldValueAsText(Fields.TitreEngField);
                    ann.Chapeau = item.GetItemListFieldValueAsHtml(Fields.ChapeauEngNewsField); 
                }
            }
            else
            {
                ann.Titre = item.GetItemListFieldValueAsText(Fields.TitreEngField);
                ann.Chapeau = item.GetItemListFieldValueAsHtml(Fields.ChapeauEngNewsField); 
                if (string.IsNullOrEmpty(ann.Titre) || string.IsNullOrEmpty(ann.Chapeau))
                {
                    ann.Titre = item.GetItemListFieldValueAsText(Fields.TitleField);
                    ann.Chapeau = item.GetItemListFieldValueAsHtml(Fields.ChapeauNewsField);
                }
            }

            string piwikTitle = item.GetItemListFieldValueAsText(Fields.TitleField);
            //ann.Titre = item.GetItemListFieldValueAsText(Fields.TitleField);

            ann.TitrePiwik = piwikTitle.Replace("/", "-").Replace("'", "\\'").Replace("\"", "\\'");
            ann.TitreCourt = GetValueShortText(ann.Titre, LengthTitreCourt);
            
            //ann.Chapeau = item.GetItemListFieldValueAsHtml(Fields.ChapeauNewsField);
            
            ann.ChapeauCourt = GetValueShortText(ann.Chapeau, 200);
            ann.Categorie = VPLink2013SPHelper.GetValue(item, Fields.CategorieNewsField);
            if (ann.Categorie.Equals("Quizz"))
            {
                string relatedNewsId = item.GetItemListLookUpFieldId(Fields.NewsQuizzField).ToString();
                ann.QuizzNews = string.Format("{0}/Pages/AnnonceDetail2013.aspx?ItemID={1}", ParamSharepointSite, relatedNewsId);
            }
            ann.DatePublication = item.GetItemListFieldValueAsDateTime(Fields.DatePublicationField);
            ann.Photo1 = item.GetItemListFieldValueAsUrlValue(Fields.Photo1Field);
            ann.Photo2 = item.GetItemListFieldValueAsUrlValue(Fields.Photo2Field);
            ann.Photo3 = item.GetItemListFieldValueAsUrlValue(Fields.Photo3Field);
            ann.Video = item.GetItemListFieldValueAsText(Fields.VideoField);
            return ann;
        }

        private void ProcessNewsVP(SPList lst, bool isFrenchVersion)
        {
            string strListe = lst.Title;
            SPQuery spQuery = new SPQuery();
            StringBuilder sb = new StringBuilder();

            string strItemID = ParamFrm("ItemID");

            string strDateCrt = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now);
            sb.Append("<Where>");
            if (strItemID != "")
            {
                sb.Append("<Eq><FieldRef Name='ID'/><Value Type='Number'>" + strItemID + "</Value></Eq>");
            }
            else
            {
                sb.AppendLine("<And>");
                sb.AppendLine("     <Eq><FieldRef Name='En_x0020_ligne'/><Value Type='Text'>Oui</Value></Eq>");
                sb.AppendLine("     <Or>");
                sb.AppendLine("         <Leq><FieldRef Name='Date_x0020_publication'/><Value Type='DateTime' IncludeTimeValue='True'>" + strDateCrt + "</Value></Leq>");
                sb.AppendLine("         <IsNull><FieldRef Name='Date_x0020_publication'/></IsNull>");
                sb.AppendLine("     </Or>");
                sb.AppendLine("</And>");
            }
            sb.Append("</Where>");
            sb.Append("<OrderBy><FieldRef Name='Date_x0020_publication' Ascending='FALSE'/><FieldRef Name='ID' Ascending='FALSE'/></OrderBy>");

            string Query = sb.ToString();
            spQuery.Query = Query;
            spQuery.RowLimit = 400;

            SPListItemCollection items = lst.GetItems(spQuery);
            foreach (SPListItem item in items)
            {
                Annonce ann = GetAnnonceFromNewsItem(item, isFrenchVersion);

                if (CompteurDerniersArticles <= 0 && GroupeALaUne && GroupeN2 && GroupeN3 && GroupeN4)
                {
                    break;
                }
                else
                {
                    if (!NewsAll)
                    {
                        SetGroupe(ann);
                    }
                    else
                    {
                        ann.Groupe = "N5";
                    }
                    if (!string.IsNullOrEmpty(ann.Groupe))
                    {
                        global.ListeAnnonces.Add(ann);
                    }
                }
            }
        }
        
        private void SetGroupe(Annonce ann)
        {
            //ContextTrace.AddTrace("SetGroupe.ann.Groupe : " + ann.Groupe);
            //ancienne version
            if (!NewsOnly2LevelActive)
            {

                if (ann.Position == "1" && !GroupeALaUne)
                {
                    ann.Groupe = "N1";
                    GroupeALaUne = true;
                    return;
                }

                if (ann.Position == "2" && !GroupeN2)
                {
                    ann.Groupe = "N2";
                    GroupeN2 = true;
                    return;
                }

                if (ann.Position == "3" && !GroupeN3)
                {
                    ann.Groupe = "N3";
                    GroupeN3 = true;
                    return;
                }

                if (ann.Position == "4" && !GroupeN4)
                {
                    ann.Groupe = "N4";
                    GroupeN4 = true;
                    return;
                }

                if (CompteurDerniersArticles <= 0)
                {
                    return;
                }
                CompteurDerniersArticles -= 1;
                ann.Groupe = "N5";
            }
            //nouvelle version
            else
            {


                if (ann.Position == "1" && !GroupeALaUne)
                {
                    ann.Groupe = "N1";
                    GroupeALaUne = true;
                    return;
                }

                if (ann.Position == "2" && CompteurGroupe2 < 3)
                {

                    switch (CompteurGroupe2)
                    {
                        case 0:
                            ann.Groupe = "N2";
                            break;
                        case 1:
                            ann.Groupe = "N3";
                            break;
                        case 2:
                            ann.Groupe = "N4";
                            break;
                    }

                    CompteurGroupe2++;
                    return;
                }

                if (CompteurDerniersArticles <= 0)
                {
                    return;
                }
                CompteurDerniersArticles -= 1;
                ann.Groupe = "N5";
            }
        }


        private string GetValueShortText(string titre, int len)
        {
            string strTitreCourt = titre;
            if (strTitreCourt.Length - 3 > len)
            {
                int iPos = strTitreCourt.IndexOf(" ", len - 3);
                if (iPos > 0)
                {
                    strTitreCourt = strTitreCourt.Substring(0, iPos) + "...";
                }
            }
            return strTitreCourt;
        }

    }
}
